package com.malty.gateway.utils;

import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import reactor.core.publisher.Mono;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author malty
 */
public class RequestBodyUtils {

    /**
     * 读取请求体字符串（异步）
     * 注意：请求体只能读取一次，使用后需缓存或确保不会二次消费
     *
     * @param request ServerHttpRequest
     * @return Mono<String> 请求体字符串，若无请求体返回空字符串
     */
    public static Mono<String> readBodyAsString(ServerHttpRequest request) {
        return DataBufferUtils.join(request.getBody())
                .map(dataBuffer -> {
                    byte[] bytes = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(bytes);
                    DataBufferUtils.release(dataBuffer);
                    return new String(bytes, StandardCharsets.UTF_8);
                })
                .defaultIfEmpty("");
    }

    /**
     * 判断请求体是否为空（异步）
     *
     * @param request ServerHttpRequest
     * @return Mono<Boolean> true 表示请求体为空，false表示有内容
     */
    public static Mono<Boolean> isBodyEmpty(ServerHttpRequest request) {
        return readBodyAsString(request)
                .map(body -> body.trim().isEmpty());
    }

    public static Map<String, String> parseFormUrlEncoded(String body) {
        Map<String, String> result = new HashMap<>();
        if (body == null || body.isEmpty()) {
            return result;
        }
        Arrays.stream(body.split("&"))
                .forEach(pair -> {
                    int idx = pair.indexOf('=');
                    try {
                        if (idx > 0) {
                            String key = URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.toString());
                            String value = URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.toString());
                            result.put(key, value);
                        } else if (idx == -1 && !pair.isEmpty()) {
                            // 参数没有值，例如 "key"
                            result.put(URLDecoder.decode(pair, StandardCharsets.UTF_8.toString()), "");
                        }
                    } catch (Exception e) {
                        System.err.println("Error decoding form-urlencoded pair: " + pair + ", " + e.getMessage());
                    }
                });
        return result;
    }
}
